package com.solo.game.snake;

import java.awt.Point;
import java.util.ArrayList;

import javax.swing.JButton;

/**
 * 
 *  <code>Snake</code>
 *  <p>Snake描述: 蛇
 *  
 *  @version 1.0 
 *  @author Zangrong.Solo 
 *  日期: Dec 19, 2012 2:11:19 PM
 */
public class Snake {
    // 蛇头
    private Point head = new Point();
    
    private Game game;

    public ArrayList<JButton> body = new ArrayList<JButton>(); // 蛇身队列
    
    
    public Snake(Game game) {
        this.game = game;
    }
    
    public void add(JButton node)
    {
        body.add(node);
    }
    
    public void addTail(JButton field)
    {
        body.add(0, field);
    }
    
    public void setHead(int x, int y)
    {
        this.head.setLocation(x, y);
    }
    
    
    public Point getHeadPoint() {
        return head;
    }

    public JButton getTail() {

        return body.get(0);
    }
    
    private void removeTail()
    {
        body.remove(0);
    }

    /**
     * 
     * <P>描述: 蛇的头部逻辑处理
     * 
     * @author Zangrong.Solo
     * 日期: Dec 19, 2012 11:53:01 AM
     * @param x
     * @param y
     */
    public void processHead(int x, int y) {
        // 新的头部坐标
        head.move(x, y);
        JButton node = this.game.getField(x, y);
        // 设置新头部的颜色
        node.setBackground(this.game.getPreference().getSnakeHeadColor());
        // 增加头部节点
        add(node);
        // 设置被占用
        this.game.setFieldAvailable(x, y, false);
    }

    /**
     * 
     * <P>描述: 蛇的尾部逻辑处理
     * 
     * @author Zangrong.Solo
     * 日期: Dec 19, 2012 11:57:21 AM
     * @param x
     * @param y
     * @return
     */
    public Point processTail(int x, int y) {
        JButton tail = getTail();
        // 找出旧尾巴的坐标
        Point point = game.getPoint(tail);
        // 清除颜色
        tail.setBackground(this.game.getPreference().getGroundColor());
        // 去掉节点
        removeTail();
        // 标记坐标位置未被占用
        game.setFieldAvailable(point.x, point.y, true);
        return point;
    }
}
